#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> 
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <string.h>

#define S_PORT 8080
#define BUFSIZ 8192

struct s_info{

	struct sockaddr_in c_addr;
	int cfd;
};

void *pthread_handler(void* arg){

	struct s_info *p = (struct s_info *)arg;
	int ret,i;
	char buf[BUFSIZ],c_IP[1024];

	printf("client ip:%s,port:%d\n",
		inet_ntop(AF_INET,&(p->c_addr.sin_addr.s_addr),c_IP,sizeof(c_IP)),
		ntohs(p->c_addr.sin_port));

	while(1){
			//5. read
			ret = read(p->cfd,&buf,sizeof(buf));

			write(STDOUT_FILENO, buf, ret);
			//6. toupper
			for(i = 0;i<ret;i++)
				buf[i] = toupper(buf[i]);
			//7. write
			write(p->cfd,buf,ret);

	}

	close(p->cfd);
	return (void *)0;
}



int main(){

	int ret;
	int sfd;
	int cfd;
	int i=0;
	socklen_t c_addr_len;
	pthread_t t1;
	struct sockaddr_in s_addr;
	struct sockaddr_in c_addr;
	struct s_info t1_info[256];

	//1. socket
	sfd = socket(AF_INET,SOCK_STREAM,0);
	//2. bind	
	bzero(&s_addr,sizeof(s_addr));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(S_PORT);
	s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(sfd,(struct sockaddr *)&s_addr,sizeof(s_addr));

	//3. litsen
	listen(sfd,3);

	//4. aceept
	while(1){
		c_addr_len = sizeof(c_addr);
		cfd = accept(sfd,(struct sockaddr *)&c_addr,&c_addr_len);
		
		t1_info[i].cfd = cfd;
		t1_info[i].c_addr = c_addr;

		pthread_create(&t1,NULL,pthread_handler,(void *)&t1_info[i]);
		pthread_detach(t1);
		
	}
	return 0;
}
